﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.ComponentModel;

namespace ImageCropper
{
    public class ImageTiler : Canvas
    {
        public ImageTiler()
        {            
            this.SizeChanged += new SizeChangedEventHandler(CheckedPanel_SizeChanged);
            this.Loaded += new RoutedEventHandler(ImageTiler_Loaded);
        }

        void ImageTiler_Loaded(object sender, RoutedEventArgs e)
        {
            _DrawChecks(new Size(0, 0), new Size(this.ActualWidth, this.ActualHeight));   
        }

        public ImageSource ImageSource { get; set; }

        void CheckedPanel_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            _DrawChecks(e.PreviousSize, e.NewSize);   
        }

        public bool IsDesignTime()
        {
            return DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual);
        }

        private void _DrawChecks(Size oldSize, Size newSize)
        {
            if (!IsDesignTime()) //this code crashes the designer
            {
                BitmapSource bs = this.ImageSource as BitmapSource;
                if (bs != null)
                    for (int y = 0; y < this.ActualHeight + bs.PixelHeight; y += bs.PixelHeight)
                        for (int x = 0; x < this.ActualWidth + bs.PixelWidth; x += bs.PixelWidth)
                        {
                            Image img = new Image();
                            img.Source = this.ImageSource;
                            Canvas.SetLeft(img, x);
                            Canvas.SetTop(img, y);
                            this.Children.Add(img);
                        }
            }
        }
    }
}
